package com.frank.player.media;

import android.text.TextUtils;

import com.frank.player.listener.OnErrorListener;
import com.frank.player.listener.OnPreparedListener;

/**
 * @Author : Frank Wu
 * @Create : 2019-09-14 17:16
 * @Email ; wu.fanguitar@163.com
 * @Description :
 */
public class AudioPlayer {
    static {
        System.loadLibrary("player");
    }

    /**
     * url 可以是本地文件路径，也可以是 http 链接
     */
    private String mUrl;
    private OnErrorListener mOnErrorListener;

    private OnPreparedListener mOnPreparedListener;

    public void setOnErrorListener(OnErrorListener onErrorListener) {
        this.mOnErrorListener = onErrorListener;
    }

    public void setOnPreparedListener(OnPreparedListener onPreparedListener) {
        this.mOnPreparedListener = onPreparedListener;
    }

    // called from jni
    private void onError(int code, String msg) {
        if (mOnErrorListener != null) {
            mOnErrorListener.onError(code, msg);
        }
    }

    // called from jni
    private void onPrepared() {
        if (mOnPreparedListener != null) {
            mOnPreparedListener.onPrepared();
        }
    }

    public void setDataSource(String url) {
        this.mUrl = url;
    }

    public void play() {
        if (TextUtils.isEmpty(mUrl)) {
            throw new NullPointerException("url is null, please call method setDataSource");
        }

        nPlay();
    }

    private native void nPlay();

    public void prepare() {
        if (TextUtils.isEmpty(mUrl)) {
            throw new NullPointerException("url is null, please call method setDataSource");
        }
        nPrepare(mUrl);
    }

    /**
     * 异步准备
     */
    public void prepareAsync() {
        if (TextUtils.isEmpty(mUrl)) {
            throw new NullPointerException("url is null, please call method setDataSource");
        }
        nPrepareAsync(mUrl);
    }

    private native void nPrepareAsync(String url);

    private native void nPrepare(String url);
}
